package com.gsn.name;

import java.net.URI;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.CookieStore;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.protocol.ClientContext;
import org.apache.http.cookie.Cookie;
import org.apache.http.entity.BufferedHttpEntity;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;

import com.gsn.dataCommon.UserData;

public class SessionkeyZingMe {
	public static String getSessionkeyUser(String userName, String passWord, boolean longtime) throws Exception {
		HttpClient httpclient = new DefaultHttpClient();
		String session = null;
		try {
			// create a local instance of cookies store
			CookieStore cookiesStore = new BasicCookieStore();
			HttpContext context = new BasicHttpContext();
			context.setAttribute(ClientContext.COOKIE_STORE, cookiesStore);

			// Connect
			HttpPost httpPost = new HttpPost();

			httpPost.setURI(new URI("https://sso2.zing.vn/index.php?method=login"));

			List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
			nameValuePairs.add(new BasicNameValuePair("pid", "25"));
			nameValuePairs.add(new BasicNameValuePair("u1", "http://login.me.zing.vn/login/success"));
			nameValuePairs.add(new BasicNameValuePair("pt", "http://login.me.zing.vn/login/fail"));
			nameValuePairs.add(new BasicNameValuePair("u", userName));
			nameValuePairs.add(new BasicNameValuePair("p", passWord));
			nameValuePairs.add(new BasicNameValuePair("longtime", String.valueOf(longtime ? 1 : 0)));

			httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

			HttpResponse respones = httpclient.execute(httpPost, context);

			System.out.print("----------------------------");
			List<Cookie> cookies = cookiesStore.getCookies();
			for (int i = 0; i < cookies.size(); i++) {
				System.out.println("Cookie : " + cookies.get(i).toString());

				if ("ZAUTH".equals(cookies.get(i).getName())) {
					session = cookies.get(i).getValue();
					System.out.println("Session : " + cookies.get(i).toString());
					return session;
				}
			}

			HttpPost post = new HttpPost("http://login.me.zing.vn/login/success");
			respones = httpclient.execute(post, context);

			System.out.print("----------------------------");
			cookies = cookiesStore.getCookies();
			for (int i = 0; i < cookies.size(); i++) {
				System.out.println("Cookie : " + cookies.get(i).toString());

				if ("ZAUTH".equals(cookies.get(i).getName())) {
					session = cookies.get(i).getValue();
					System.out.println("Cookie Session Value : " + cookies.get(i).getValue());
					return session;
				}
			}

		} catch (Exception e) {
			e.printStackTrace();
			httpclient.getConnectionManager().shutdown();
			throw e;
		}

		httpclient.getConnectionManager().shutdown();
		return session;

	}

	public static JSONObject getInfo() throws Exception {
		JSONObject json = null;
		try {
			CookieStore cookiesStore = new BasicCookieStore();
			cookiesStore.clear();
			HttpContext context = new BasicHttpContext();
			context.setAttribute(ClientContext.COOKIE_STORE, cookiesStore);

			HttpParams my_httpParams = new BasicHttpParams();
			HttpConnectionParams.setConnectionTimeout(my_httpParams, 5000);
			HttpConnectionParams.setSoTimeout(my_httpParams, 5000);
			HttpClient httpclient = new DefaultHttpClient(my_httpParams);

			HttpPost httpPost = new HttpPost();
			httpPost.setURI(new URI("http://myplay.apps.zing.vn/portal/Api.php?session_id=" + UserData.sessionKey));
			HttpResponse respones = httpclient.execute(httpPost, context);

			HttpEntity entity = respones.getEntity();
			if (entity != null) {
				System.out.println("Response content Length" + entity.getContentLength());
				HttpEntity temp = respones.getEntity();
				if (temp != null) {
					HttpEntity e = new BufferedHttpEntity(temp);
					String responseBody = EntityUtils.toString(e, "UTF-8");
					System.out.println(" in ne : " + responseBody + "!!!");
					String s = responseBody;
					while (s.length() > 0 && !(s.charAt(0) == '{')) {
						System.out.println("char 0 : " + s.charAt(0));
						s = s.substring(1);
					}
					if (s.equals(""))
					{
						System.out.println("xau s null roi");
						return null;
					}
					try {
						System.out.println("thu lay json ");
						json = new JSONObject(s);
						System.out.println("lay json thanh cong");
					} catch (Exception e1) {
						// TODO: handle exception
						e1.printStackTrace();
						return null;
					}
				}
			}

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			throw e;
		}
		return json;
	}

	public static void main(String[] args) throws Exception {
		System.out.println("session : " + getSessionkeyUser("simo06", "handoi", true));
	}
}
